<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

	var $helpers = array('Form', 'Html', 'Session', 'Js' => array('Jquery'));
	public $components = array('Session', 'Paginator', 'RequestHandler', 'Cookie', 'Auth' => array(
            'loginRedirect' => array('controller' => 'home', 'action' => 'index'),
            //'loginRedirect' => array('controller' => 'Pages', 'action' => 'home'),
            'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
			));
			
			
	public $is_mobile = false;
	public $layouts = array('desktop', 'mobile');
	
	function beforeFilter() 
  {
	//VIEW SETTINGS FOR USERS NOT LOGGED IN
	//$this->Set->('current_user', $this->Auth->user());
	
	$utype = CakeSession::read("Auth.User.UserType");
	$this->Auth->deny();
	if (CakeSession::read("Auth.User.UserType") != 'Administrator' ) {

			
	}
	if (CakeSession::read("Auth.User.UserType") == 'Contact Worker' ) {
	$this->Auth->allow('view', 'index');		
	}
	
	
	
    // Using "rijndael" encryption because the default "cipher" type of encryption fails to decrypt when PHP has the Suhosin patch installed. 
    // See: http://cakephp.lighthouseapp.com/projects/42648/tickets/471-securitycipher-function-cannot-decrypt
    $this->Cookie->type('rijndael');

    // When using "rijndael" encryption the "key" value must be longer than 32 bytes.
    $this->Cookie->key = 'qSI24233f43fv42asdasdadad34SasdadAWQEAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^'; // When using rijndael encryption this value must be longer than 32 bytes.

    // Flag whether the layout is being "forced" i.e overwritten/controlled by the user (true or false)
    $forceLayout = $this->Cookie->read('Options.forceLayout');

    // Identify the layout the user wishes to "force" (mobile or desktop)
    $forcedLayout = $this->Cookie->read('Options.forcedLayout');

    // Check URL paramaters for ?forcedLayout=desktop or ?forcedLayout=mobile and persist this decision in a COOKIE
    if( isset($this->params->query['forcedLayout']) && in_array($this->params->query['forcedLayout'], $this->layouts) )
    {
        $forceLayout = true;
        $forcedLayout = $this->params->query['forcedLayout'];
        $this->Cookie->write('Options.forceLayout', $forceLayout);
        $this->Cookie->write('Options.forcedLayout', $forcedLayout);
    }

    // We use CakePHP's built in "mobile" User-Agent detection (a pretty basic list of UA's see: /lib/Cake/Network/CakeRequest.php)
    // Note: For more robust detection consider using "Mobile Detect" (https://github.com/serbanghita/Mobile-Detect) or WURL (http://wurfl.sourceforge.net/)
    if( ( $forceLayout && $forcedLayout == 'mobile' ) || ( !$forceLayout && $this->request->is('mobile') ) )  {
        $this->is_mobile = true;
        $this->autoRender = false; // take care of rendering in the afterFilter()
    }

    $this->set('is_mobile', $this->is_mobile);
  }

  // executed after all controller logic, including the view render.
  function afterFilter() {


    // if in mobile mode, check for a vaild layout and/or view and use it
    if( $this->is_mobile ) {
        $has_mobile_view_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . $this->name . DS . 'mobile' . DS . $this->action . '.ctp' );
        $has_view_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . $this->name . DS . $this->action . '.ctp' );
        $has_mobile_layout_file = file_exists( ROOT . DS . APP_DIR . DS . 'View' . DS . 'Layouts' . DS . 'mobile' . DS . $this->layout . '.ctp' );

        if($has_mobile_view_file)
		{
			$view_file = ( $has_mobile_view_file ? 'mobile' . DS : '' ) . $this->action;
		}
		else
		{
			$view_file = ( $has_view_file ? DS : '' ) . $this->action;
		}
		
        $layout_file = ( $has_mobile_layout_file ? 'mobile' . DS : '' ) . $this->layout;
		
		$this->render( $view_file, $layout_file );
    }
  }
	
	
	function uploadFiles($folder, $formdata, $itemId = null) 
	{
		// setup dir names absolute and relative
		$folder_url = WWW_ROOT.$folder;
		$rel_url = $folder;
		
		// create the folder if it does not exist
		if(!is_dir($folder_url)) {
			mkdir($folder_url);
		}
			
		// if itemId is set create an item folder
		if($itemId) {
			// set new absolute folder
			$folder_url = WWW_ROOT.$folder.'/'.$itemId; 
			// set new relative folder
			$rel_url = $folder.'/'.$itemId;
			// create directory
			if(!is_dir($folder_url)) {
				mkdir($folder_url);
			}
		}
		
		// list of permitted file types, this is only images but documents can be added
		//$permitted = array('image/gif','image/jpeg','image/pjpeg','image/png');
		
		// list of permitted file types
			$permitted = array(
							'image/jpeg',
							'application/pdf',
							'text/pdf',
							'txt/pdf',
							'application/msword',
							'application/octet-stream',
							'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
							'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
							'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
							'application/vnd.openxmlformats-officedocument.presentationml.presentation',
							'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
							'application/msword');
							
		
		// loop through and deal with the files

			// replace spaces with underscores
			$filename = str_replace(' ', '_', $formdata['name']);
			// assume filetype is false
			$typeOK = false;
			// check filetype is ok
			foreach($permitted as $type) {
				if($type == $formdata['type']) {
					$typeOK = true;
					break;
				}
			}
			
			// if file type ok upload the file
			if($typeOK) {
				// switch based on error code
				switch($formdata['error']) {
					case 0:
						// check filename already exists
						if(!file_exists($folder_url.'/'.$filename)) {
							// create full filename
							$full_url = $folder_url.'/'.$filename;
							$url = $rel_url.'/'.$filename;
							// upload the file
							$success = move_uploaded_file($formdata['tmp_name'], $url);
						} else {
							// create unique filename and upload file
							ini_set('date.timezone', 'Europe/London');
							$now = date('Y-m-d-His');
							$full_url = $folder_url.'/'.$now.$filename;
							$url = $rel_url.'/'.$now.$filename;
							$success = move_uploaded_file($formdata['tmp_name'], $url);
						}
						// if upload was successful
						if($success) {
							// save the url of the file
							$result['urls'][] = $url;
							$result['type'][] = $formdata['type'];
						} else {
							$result['errors'][] = "Error uploaded $filename. Please try again.";
						}
						break;
					case 3:
						// an error occured
						$result['errors'][] = "Error uploading $filename. Please try again.";
						break;
					default:
						// an error occured
						$result['errors'][] = "System error uploading $filename. Contact webmaster.";
						break;
				}
			} elseif($formdata['error'] == 4) {
				// no file was selected for upload
				$result['nofiles'][] = "No file Selected";
			} else {
				// unacceptable file type
				$result['errors'][] = "$filename cannot be uploaded. Acceptable file types: gif, jpg, png.";
			}
	return $result;
	}
	
		

		
	
}
